package com.kefu.service.impl;

import com.kefu.dto.UserDTO;
import com.kefu.dto.UserLoginRequest;
import com.kefu.entity.User;
import com.kefu.repository.UserRepository;
import com.kefu.service.UserService;
import com.kefu.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private JwtUtil jwtUtil;

    // 生成带随机数的匿名昵称（匿名用户+4位随机数）
    private String generateAnonymousNickname() {
        Random random = new Random();
        // 生成1000-9999之间的随机数
        int randomNum = 1000 + random.nextInt(9000);
        return "匿名用户" + randomNum;
    }


    @Override
    public Map<String, Object> login(UserLoginRequest request) {
        User user = null;

        // 匿名登录(无密码)
        if (request == null ||request.getCode() == null || request.getCode().isEmpty()) {
            // 生成临时用户ID
            String userId =  UUID.randomUUID().toString().replace("-", "");
            user = new User();
            user.setId(userId);
            user.setNickname(generateAnonymousNickname());
            user.setAnonymous(true);
            userRepository.save(user);
        }
        // 手机号登录
        else if("123456".equals(request.getCode()) && !request.getPhone().isEmpty()) {
            user = userRepository.findByPhone(request.getPhone());
            if(user == null ) {
                // 生成临时用户ID
                String userId = "anon_" + UUID.randomUUID().toString().replace("-", "");
                user = new User();
                user.setId(userId);
                user.setPhone(request.getPhone());
                user.setNickname(request.getPhone());
                user.setAnonymous(true);
                userRepository.save(user);
            }
        }

        // 生成token
        // String token = jwtUtil.generateToken(user.getId());

        // 最简单的方式：用户ID+当前时间戳拼接作为token
        String token = user.getId() + "_" + System.currentTimeMillis();

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);

        UserDTO userDTO = new UserDTO();
        userDTO.setId(user.getId());
        userDTO.setPhone(user.getPhone());
        userDTO.setNickname(user.getNickname());
        userDTO.setAvatar(user.getAvatar());
        result.put("user", userDTO);

        return result;
    }

    @Override
    public UserDTO getUserById(String userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        UserDTO dto = new UserDTO();
        dto.setId(user.getId());
        dto.setPhone(user.getPhone());
        dto.setNickname(user.getNickname());
        dto.setAvatar(user.getAvatar());
        return dto;
    }
}
